package com.lonwin.inspectionmanagement.mvp.presenter;

import android.app.Application;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.functions.Function;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import retrofit2.http.PUT;

import javax.inject.Inject;

import com.jess.arms.utils.DataHelper;
import com.lonwin.inspectionmanagement.app.AppConstants;
import com.lonwin.inspectionmanagement.app.utils.DataUtil;
import com.lonwin.inspectionmanagement.app.utils.RxUtils;
import com.lonwin.inspectionmanagement.mvp.contract.CreatPointRecordContract;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.BaseBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.CreaQuestResultBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ImageBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.NoSortOutBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.PointHistoryBean;

import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ResQdetailBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.UploadBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.SaveResultBean;
import com.lonwin.inspectionmanagement.widget.voicerecorder.utils.PathUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@ActivityScope
public class
CreatPointRecordPresenter extends BasePresenter<CreatPointRecordContract.Model, CreatPointRecordContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    Gson mGson;
    ConfigBean configBean;

    @Inject
    public CreatPointRecordPresenter(CreatPointRecordContract.Model model, CreatPointRecordContract.View rootView) {
        super(model, rootView);
         configBean= DataHelper.getDeviceData(mRootView.getActivity(), AppConstants.EXTRA_CONFIG_DATA);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void initPhoto(){
        List<ImageBean> datas=new ArrayList<>();
        datas.add(new ImageBean());
        datas.add(new ImageBean());
        datas.add(new ImageBean());
        datas.add(new ImageBean());
        mRootView.initPicRecylerView(datas);
    }


    public void startRecord(){
        PathUtil.getInstance().createDirs("chat", "voice", mApplication);

    }
    public void savePoints(ResQdetailBean.DataBean dataBean, boolean isSave, String relid)
    {
        Map<String,String> mpas=new HashMap<>();

        if (isSave&&!TextUtils.isEmpty(relid))
        {
            //是保存业务
            try {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("reltype","0");
                jsonObject.put("relid",relid);//巡查id
                mpas.put("questrel",jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        mpas.put("quest", new Gson().toJson(dataBean));
//        if (isSave)
//        {
            mModel.savePointData(DataUtil.getJNUrl(configBean)+"/webmvc/v1/taskhzz/saveQuest",mpas)
                    .compose(RxUtils.applySchedulers(mRootView))
                    .subscribe(new ErrorHandleSubscriber<SaveResultBean>(mErrorHandler) {
                        @Override
                        public void onNext(SaveResultBean saveResultBean) {
                            mRootView.savePointDataSuccess(saveResultBean);
                        }
                    });
//            return;
//        }
//
//        editPoint(configBean,mpas);
    }

    /**
     * 编辑
     * @param configBean
     * @param maps
     */
    public void editPoint(ConfigBean configBean,Map<String,String> maps){
        mModel.editPoint(DataUtil.getJNUrl(configBean)+"/webmvc/v1/taskhzz/saveQuest",maps)
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<PointHistoryBean.DataBean>(mErrorHandler) {
                    @Override
                    public void onNext(PointHistoryBean.DataBean dataBean) {
                        mRootView.editPointSuccess(dataBean);
                    }
                });
    }

    /**
     * 上传照片文件
     */
    public void uploadFile(File file,int type){
        mModel.uploadFile(DataUtil.getFileUrl(configBean),file).compose(RxUtils.applySchedulers(mRootView)).subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
            @Override
            public void onNext(String s) {
                   if (type==1){
                        mRootView.imgUpSuccess(s);
                    }else if(type==2) {
                        mRootView.audioUpSuccess(s);
                    }else if (type==3){
                       mRootView.videoUpSuccess(s);
                   }else if (type==4){
                       mRootView.videoPicUpSuccess(s);
                   }
            }
        });
//        mModel.uploadFile(file).compose(RxUtils.applySchedulers(mRootView))
//                .map(new Function<String, UploadBean>() {
//                    @Override
//                    public UploadBean apply(String s) throws Exception {
//                        return mGson.fromJson(s,UploadBean.class);
//                    }
//                })
//                .subscribe(new ErrorHandleSubscriber<UploadBean>(mErrorHandler) {
//                    @Override
//                    public void onNext(UploadBean uploadBean) {
//                        if (uploadBean.getCode()==0){
//                            if (isphoto){
//                                mRootView.imgUpSuccess(uploadBean.getData().getPath());
//                            }else {
//                                mRootView.audioUpSuccess(uploadBean.getData().getPath());
//                            }
//                        }
//                    }
//                });
    }
//=========================================================================================================================
    /**
     * 创建问题记录
     * @param maps
     */
    public void creaQuestResult(Map<String,Object> maps){
//        String url="http://hzz.lonhcloud.cn/hzxh/questTempController/addQuestTemp";
        if (getConfigBean().getRiverDatas()!=null&&getConfigBean().getRiverDatas().size()==1&&getConfigBean().getRiverDatas().get(0).getChildren()!=null&&getConfigBean().getRiverDatas().get(0).getChildren().size()==1)
        {
            //只有一条河getRiverDatas().get(0)
            maps.put("groupid",getConfigBean().getRiverDatas().get(0).getChildren().get(0).getId());
            maps.put("groupnm",getConfigBean().getRiverDatas().get(0).getChildren().get(0).getName());
        }
                String url=DataUtil.getJNUrl(configBean)+"/hzxh/questTempController/addQuestTemp";
        mModel.addQuestTemp(url,maps).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<CreaQuestResultBean>(mErrorHandler) {
                    @Override
                    public void onNext(CreaQuestResultBean creaQuestResultBean) {
                        if (creaQuestResultBean==null||creaQuestResultBean.getCode()!=0)
                        {
                            mRootView.showMessage("添加异常");
                            return;
                        }
                        mRootView.addQuestTempSuccess(creaQuestResultBean.getData());
                    }
                });
    }

    public void loadDetail(String id){
        String url=DataUtil.getJNUrl(configBean)+"/hzxh/questTempController/getQuestTemp";
        mModel.loadDetail(url,id).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResQdetailBean>(mErrorHandler) {
                    @Override
                    public void onNext(ResQdetailBean resQdetailBean) {
                        if (resQdetailBean==null||resQdetailBean.getCode()!=0)
                        {
                            mRootView.showMessage("接口异常");
                            return;
                        }
                        mRootView.setDetailBean(resQdetailBean.getData());
                    }
                });
    }

    /**
     * 公开
     */

    public void  publishPoint(String id){
        String url=DataUtil.getJNUrl(configBean)+"/hzxh/questTempController/openQuestTemp";
        mModel.publishQuestion(url,id).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResQdetailBean>(mErrorHandler) {
                    @Override
                    public void onNext(ResQdetailBean resQdetailBean) {
                        mRootView.publishSuccess(resQdetailBean);
                    }
                });
    }


    /**
     * 删除
     */
    public void deletePoint(String id){
        String url=DataUtil.getJNUrl(configBean)+"/hzxh/questTempController/deleteQuestTemp";
        mModel.deleteQuestion(url,id).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseBean>(mErrorHandler) {
                    @Override
                    public void onNext(BaseBean baseBean) {
                        mRootView.deleteSuccess();
                    }
                });
    }


    /**
     * 修改成功
     */

    public void updatePoint(ResQdetailBean.DataBean resQdetailBean){
        String url=DataUtil.getJNUrl(configBean)+"/hzxh/questTempController/editQuestTemp";
        mModel.updateQuestion(url,resQdetailBean).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResQdetailBean>(mErrorHandler) {
                    @Override
                    public void onNext(ResQdetailBean resQdetailBean) {
                        mRootView.updateSuccess(resQdetailBean);
                    }
                });
    }

    public ConfigBean getConfigBean() {
        return configBean;
    }
}
